package com.tmc.service.intcar;

import java.util.Date;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.tmc.bean.common.CommonResult;
import com.tmc.bean.common.ContextInfo;
import com.tmc.constant.IntcarOrderConstant;
import com.tmc.constant.OrderConstant;
import com.tmc.dao.impl.intcar.IntcarAdditionalServiceDaoImpl;
import com.tmc.dao.impl.intcar.IntcarDriverDaoImpl;
import com.tmc.dao.impl.intcar.IntcarOrderDaoImpl;
import com.tmc.dao.impl.intcar.IntcarPassengerDaoImpl;
import com.tmc.entity.intcar.IntcarAdditionalService;
import com.tmc.entity.intcar.IntcarDriver;
import com.tmc.entity.intcar.IntcarOrder;
import com.tmc.entity.intcar.IntcarPassenger;
import com.tmc.util.DateUtil;
import com.tmc.util.ObjectUtil;



/**
 * @author zhang
 * @date 2017年12月14日 下午5:59:16 
 */
@Service
@Transactional
public class IntcarOrderServiceImpl {
	
	private Log log = LogFactory.getLog(IntcarOrderServiceImpl.class);
	
	@Autowired 
	private IntcarOrderDaoImpl orderDao;
	
	@Autowired
	private IntcarPassengerDaoImpl passengerDao;
	
	@Autowired
	private IntcarAdditionalServiceDaoImpl serviceDao;
	
	@Autowired
	private IntcarDriverDaoImpl driverDao;
	
	@Autowired
	private IntcarDriverServiceImpl driverService;

	public IntcarOrder getById(ContextInfo context, Long orderID){
		return orderDao.getById(orderID);
	}
	
	/**
	 * 保存订单
	 * @author zhang
	 * @param order
	 * @return
	 * 			CommonResult
	 */
	public CommonResult save(ContextInfo context, IntcarOrder order) {
		if(order == null){
			return CommonResult.makeFail("订单不能为空！");
		}
		CommonResult checkResult = this.check(order);
		if(!checkResult.isSuccess()){
			return checkResult;
		}
		IntcarOrder dbOrder = null;
		if(order.getOrderID() != null){
			dbOrder = orderDao.getById(order.getOrderID());
		} else if(ObjectUtil.hasText(order.getVendorOrderID())){
			orderDao.getByVenderOrderID(context, order.getVendorOrderID());
		}else if(ObjectUtil.hasText(order.getOrderNum())){
			orderDao.getByOrderNum(context, order.getOrderNum());
		}
		
		if(dbOrder == null){
			//添加
			//设置订单编号          
			order.setOrderNum(this.getOrderNum(context, order.getCreationDate()));
			//设置订单状态
			order.setOrderStatus(OrderConstant.ORDER_STATUS_PAYING);
			ObjectUtil.setBaseInfo(order, context);
			orderDao.insert(order);
			if(order.getPassengerList() != null && !order.getPassengerList().isEmpty()){
				this.savePassengers(context, order);
			}
			if(order.getAdditionalServiceList() != null && !order.getAdditionalServiceList().isEmpty()){
				this.saveAdditionalServices(context, order);
			}
			if(order.getDriver() != null){
				this.saveDriver(context, order);
			}
			return CommonResult.makeSuccess("保存成功！", order);
		} else {
			//编辑
			try {
				ObjectUtil.copyProperties(order, dbOrder, new String[]{"createdBy", 
						"creationDate", "enabledFlag", "orderID", "orderNum", 
						"vendor" , "orderStatus", "carCount" });
			} catch (Exception e) {
				log.error("拷贝对象错误！", e);
				return CommonResult.makeFail("拷贝对象错误！");
			}
			ObjectUtil.updateBaseInfo(dbOrder, context);
			orderDao.update(dbOrder);
			return CommonResult.makeSuccess("保存成功！", dbOrder);
		}
		
	}
	
	
	/**
	 * 保存附司导信息
	 * 
	 * @author zhang
	 * @param context
	 * @param order
	 */
	private void saveDriver(ContextInfo context, IntcarOrder order) {
		IntcarDriver driver = order.getDriver();
		driver.setOrderID(order.getOrderID());
		ObjectUtil.setBaseInfo(driver, context);
		driverDao.insert(driver);
	}

	/**
	 * 保存附加服务费信息
	 * @author zhang
	 * @param context
	 * @param order
	 */
	private void saveAdditionalServices(ContextInfo context, IntcarOrder order) {
		for (IntcarAdditionalService service : order.getAdditionalServiceList()) {
			service.setOrderID(order.getOrderID());
			ObjectUtil.setBaseInfo(service, context);
			serviceDao.insert(service);
		}
	}

	/**
	 * 保存乘客信息
	 * @author zhang
	 * @param context
	 * @param order
	 */
	private void savePassengers(ContextInfo context, IntcarOrder order) {
		for(IntcarPassenger passenger : order.getPassengerList()){
			passenger.setOrderID(order.getOrderID());
			ObjectUtil.setBaseInfo(passenger, context);
			passengerDao.insert(passenger);
		}
	}
	
	/**
	 * 删除本地订单
	 * @author zhang
	 * @param context
	 * @param order
	 * @return CommonResult
	 */
	public CommonResult delete(ContextInfo context, IntcarOrder order) {
		IntcarOrder dbOrder = orderDao.getById(order.getOrderID());
		if(dbOrder == null){
			CommonResult.makeFail("此订单不存在！");
		}
		dbOrder.setEnabledFlag("N");
		ObjectUtil.updateBaseInfo(dbOrder, context);
		orderDao.update(dbOrder);
		return CommonResult.makeSuccess();
	}

	/**
	 * 取消本地订单
	 * @author zhang
	 * @param context
	 * @param dbOrder
	 * @return
	 */
	public CommonResult canceled(ContextInfo context, IntcarOrder order) {
		IntcarOrder dbOrder = orderDao.getById(order.getOrderID());
		if(dbOrder == null){
			CommonResult.makeFail("此订单不存在！");
		}
		dbOrder.setOrderStatus(OrderConstant.ORDER_STATUS_CANCELED);
		ObjectUtil.updateBaseInfo(dbOrder, context);
		orderDao.update(dbOrder);
		return CommonResult.makeSuccess();
	}
	
	/**
	 * 订单完成
	 * 
	 * @author zhang
	 * @param context
	 * @param order
	 * @return
	 */
	public CommonResult finished(ContextInfo context, IntcarOrder order){
		IntcarOrder dbOrder = orderDao.getById(order.getOrderID());
		if(dbOrder == null){
			CommonResult.makeFail("此订单不存在！");
		}
		dbOrder.setOrderStatus(IntcarOrderConstant.ORDER_STATUS_FINISHED);
		ObjectUtil.updateBaseInfo(dbOrder, context);
		orderDao.update(dbOrder);
		return CommonResult.makeSuccess();
	}
	
	/**
	 * 更新订单状态
	 * 
	 * @author zhang
	 * @param context
	 * @param order
	 * @return
	 */
	public CommonResult updateOrderStatus(ContextInfo context, IntcarOrder order){
		IntcarOrder dbOrder = orderDao.getById(order.getOrderID());
		if(dbOrder == null){
			CommonResult.makeFail("此订单不存在！");
		}
		dbOrder.setOrderStatus(order.getOrderStatus());
		ObjectUtil.updateBaseInfo(dbOrder, context);
		orderDao.update(dbOrder);
		return CommonResult.makeSuccess("操作成功");
	}
	
	/**
	 * 更新订单的乘客信息
	 * @author zhang
	 * @param context
	 * @param dbOrder
	 * @return
	 */
	public CommonResult updatePassenger(ContextInfo context, IntcarOrder order) {
		IntcarOrder dbOrder = orderDao.getById(order.getOrderID());
		if(dbOrder == null){
			return CommonResult.makeFail(order.getOrderID()+"的订单不存在！");
		}
		try {
			//获取联系人列表
			List<IntcarPassenger> passengers = passengerDao.findByOrderID(context, dbOrder.getOrderID());
			IntcarPassenger passenger = order.getPassengerList().get(0);
			IntcarPassenger dbPassenger = passengers.get(0);
			ObjectUtil.copyProperties(passenger, dbPassenger, new String[]{"createdBy", 
					"creationDate", "enabledFlag", "orderID", "passengerID"});
			ObjectUtil.updateBaseInfo(dbPassenger, context);
			passengerDao.update(dbPassenger);
			return CommonResult.makeSuccess();
		} catch (Exception e) {
			log.error("拷贝对象出错！", e);
			return CommonResult.makeFail("拷贝对象出错！");
		} 
		
	}
	
	/**
	 * 更新订单的司导信息(司导指派)
	 * 
	 * @author zhang
	 * @param context
	 * @param order
	 */
	public CommonResult pushDriver(ContextInfo context, IntcarOrder order) {
		CommonResult cr = driverService.save(context, order.getDriver());
		//更新订单状态
		if(cr.isSuccess()){
			CommonResult cr2 = this.updateOrderStatus(context, order);
			return cr2;
		}
		return cr;
	}

	private  String getOrderNum(ContextInfo context, Long creationDate) {
		if (creationDate == null) {
			creationDate = DateUtil.toLongDate(new Date());
		}
		String tag = "IA" + (creationDate + "").substring(2, 8);
		Long nums = this.getTodayOrdersCount(context, tag);
		return tag + this.get4CharacterNo(nums + 1);
	}

	private String get4CharacterNo(Long num) {
		String str = String.valueOf(num);
		for (int i = str.length(); i < 4; i++) {
			str = "0" + str;
		}
		return str;
	}

	private Long getTodayOrdersCount(ContextInfo context, String tag) {
		return orderDao.getTodayOrdersCount(context, tag);
	}
	
	private CommonResult check(IntcarOrder order){
		if(ObjectUtil.noText(order.getPriceMark())){
			return CommonResult.makeFail("无此价格标识！");
		}
		if(order.getCarTypeID() == null || order.getCarTypeID() == 0){
			return CommonResult.makeFail("请选择车型！");
		}
		if(order.getStaffNum() == null){
			return CommonResult.makeFail("请填写乘客数量！");
		}
		if(order.getLuggageNum() == null){
			return CommonResult.makeFail("请填写行李数量！");
		}
		if(order.getPassengerList() == null ||order.getPassengerList().isEmpty()){
			return CommonResult.makeFail("联系人信息不能为空！");
		}
		List<IntcarPassenger> passengers = order.getPassengerList();
		for (IntcarPassenger passenger : passengers) {
			if(ObjectUtil.noText(passenger.getName())){
				return CommonResult.makeFail("联系人姓名不能为空！");
			}
			if(ObjectUtil.noText(passenger.getAreaCode())){
				return CommonResult.makeFail("联系人电话国家代码不能为空！");
			}
			if(ObjectUtil.noText(passenger.getPhone())){
				return CommonResult.makeFail("联系人电话国家代码不能为空！");
			}
		}
		
		List<IntcarAdditionalService> serviceList = order.getAdditionalServiceList();
		if(serviceList != null){
			for (IntcarAdditionalService service : serviceList) {
				if(ObjectUtil.noText(service.getSid())){
					return CommonResult.makeFail("附加服务编码不能为空！");
				}
				if(service.getNumber() == null){
					return CommonResult.makeFail("数量不能为空！");
				}
				if(service.getAmount() == null){
					return CommonResult.makeFail("费用总金额不能为空！");
				}
				if(service.getPrice() == null){
					return CommonResult.makeFail("费用总金额不能为空！");
				}
			}
		}
		
		if(order.getDriver() != null){
			IntcarDriver driver = order.getDriver();
			if(ObjectUtil.noText(driver.getDriverName())){
				return CommonResult.makeFail("司导不能为空！");
			}
			if(ObjectUtil.noText(driver.getDriverCarDesc())){
				return CommonResult.makeFail("司导手机号码不能为空！");
			}
		}
		return CommonResult.makeSuccess();
	}

}
